import packageJSON from 'app/package.json'
import { LocalStorage, SessionStorage } from 'quasar'

const formatKey = (key) => {
  if (key === 'userName') return packageJSON.name
  return `${SessionStorage.getItem(packageJSON.name) || ''}--${packageJSON.name}-${key}`
}

/**
 * 存储Store
 */
export const setStore = (key, value, type = '') => {
  if (['L', 'l'].includes(type)) return LocalStorage.setItem(formatKey(String(key)), value)
  SessionStorage.setItem(formatKey(String(key)), value)
}

/**
 * 获取Store
 */
export const getStore = (key, type = '') => {
  if (['L', 'l'].includes(type)) {
    return LocalStorage.getItem(formatKey(String(key))) ?? LocalStorage.getItem(String(key))
  }
  return SessionStorage.getItem(formatKey(String(key)))
}

/**
 * 删除Store
 */
export const removeStore = (key, type = '') => {
  if (['L', 'l'].includes(type)) return LocalStorage.removeItem(formatKey(String(key)))
  SessionStorage.removeItem(formatKey(String(key)))
}

/**
 * 清空全部Store
 */
const settings = ['isDark', 'primaryBG', 'positiveBG', 'negativeBG', 'infoBG', 'warningBG', 'isDense', 'locale']

export const clearStore = clearLocal => {
  const LKeys = Object.keys(localStorage), SKeys = Object.keys(sessionStorage)
  for (const key of LKeys) {
    if (!clearLocal && settings.includes(key)) continue
    if (key.startsWith(formatKey(''))) LocalStorage.removeItem(String(key))
  }
  for (const key of SKeys) key.startsWith(formatKey('')) && SessionStorage.removeItem(String(key))
}